/*
 * @Author: yangni
 * @Date: 2023-09-19 18:46:23
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-10 16:34:14
 * @Description: EMS详情信息
 */
import 'dart:async';
import 'package:get/get.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_func_util.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import '../../../model/device_items_group_model.dart';
import 'ems_detail_model.dart';

class EmsDetailController extends BaseDetailController {
  EmsDetaiModel model = EmsDetaiModel();

  List<DeviceItemsGroupModel> group = [];

  UseSubsribe subsribe = UseSubsribe();
  Map<String, dynamic>? dataSource;
  StreamSubscription<Map<String, dynamic>>? _subscript;
  late Stream<Map<String, dynamic>> broadcastStream;

  /// 页面标题
  String title = '';

  /// 当前设备id
  int? deviceId;

  DeviceModel? deviceModel;

  @override
  void onInit() {
    super.onInit();
    connectStatus = Get.arguments['connectStatus'];
    deviceId = Get.arguments['deviceId'];

    broadcastStream =
        subsribe.start([deviceId!], true).stream.asBroadcastStream();
    _subscript = broadcastStream.listen((data) {
      Map<String, dynamic> periodMap = {};
      for (var i = 0; i < model.timeMap.keys.length; i++) {
        int index = i + 1;
        var field = model.timeMap['time$index'];
        if (data[field?[0]] != null) {
          periodMap.putIfAbsent(
            'period$index',
            () => formateTime(data[field![0]], data[field[1]], data[field[2]],
                data[field[3]]),
          );
        }
      }
      data.addEntries(periodMap.entries);
      dataSource = data;
      update();
    });
  }

  initData() async {
    title = deviceModel?.name ?? '';

    var list = await DeviceFuncUtils.getFormateByDeviceModel(
        [model.controllItems, model.protectItems], deviceModel?.productId);
    group = [
      DeviceItemsGroupModel(
          title: 'siteMonitor.controlInformation'.tr, //控制信息
          items: list[0]),
      if (deviceModel?.masterSlaveMode != MasterSlaveModeType.vice) ...[
        DeviceItemsGroupModel(
            title: 'siteMonitor.protectInformation'.tr, //控制信息
            items: list[1]),
        DeviceItemsGroupModel(
            title: 'siteMonitor.runningParameterSet'.tr, //运行参数
            items: model.runItems),
      ]
    ];

    update();
  }

  String formateTime(hour1, min1, hour2, min2) {
    var result =
        '${intToString(hour1)}:${intToString(min1)}-${intToString(hour2)}:${intToString(min2)}';
    return result;
  }

  String intToString(value) {
    if (value is int && value < 10) {
      return '0$value';
    } else {
      return value?.toString() ?? '';
    }
  }

  void goControlRomote() {
    // 跳转到远程控制页面
    Get.toNamed(
      RouterPath.selfDevelopedEmsRomoteControl,
      arguments: {'deviceId': deviceId},
    );
    update();
  }

  @override
  void onClose() {
    subsribe.closeListen();
    _subscript?.cancel();
    super.onClose();
  }
}
